package com.proactive.webapp.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.proactive.webapp.dao.LightTemplateDAO;
import com.proactive.webapp.entity.LightTemplate;

public class LightTemplateDAOImpl implements LightTemplateDAO{
	private DataSource dataSource;
	private Connection conn = null ;
	private ResultSet rs = null ;
	private PreparedStatement smt = null ;
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public List<LightTemplate> getList() {
		// TODO Auto-generated method stub
		List<LightTemplate> lightTemplateList = new ArrayList<LightTemplate>();
		String sql = "SELECT * FROM light_template";
		try {
			conn = dataSource.getConnection();
			smt = conn.prepareStatement(sql);
			rs = smt.executeQuery();
			while(rs.next()){
				LightTemplate lightTemplate = new LightTemplate();
				lightTemplate.setId(rs.getInt("lightTemplateID"));
				lightTemplate.setTitle(rs.getString("lightTemplateTitle"));
				lightTemplate.setImagePath(rs.getString("lightTemplateImage"));
				lightTemplate.setHtml1Path(rs.getString("lightTemplateHtml1"));
				lightTemplate.setHtml2Path(rs.getString("lightTemplateHtml2"));
				lightTemplateList.add(lightTemplate);
			}
			rs.close();
			smt.close();
 
		} catch (SQLException e) {
			throw new RuntimeException(e);
 
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
		return lightTemplateList;
	}
	
	public LightTemplate get(LightTemplate lightTemplate){
		String sql = "SELECT * FROM light_template WHERE lightTemplateID=?";
		try {
			conn = dataSource.getConnection();
			smt = conn.prepareStatement(sql);
			smt.setInt(1, lightTemplate.getId());
			rs = smt.executeQuery();
			if(rs.next()){		
				lightTemplate.setId(rs.getInt("lightTemplateID"));
				lightTemplate.setTitle(rs.getString("lightTemplateTitle"));
				lightTemplate.setImagePath(rs.getString("lightTemplateImage"));
				lightTemplate.setHtml1Path(rs.getString("lightTemplateHtml1"));
				lightTemplate.setHtml2Path(rs.getString("lightTemplateHtml2"));
			}
			rs.close();
			smt.close();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {}
			}
		}
		return lightTemplate;
	}
}

